package se.sll.service.catalogue.export.service;

import java.util.List;
import java.util.TreeSet;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import lombok.extern.slf4j.Slf4j;
import se.sll.service.catalogue.common.exception.ServiceCatalogueException;
import se.sll.service.catalogue.common.exception.ServiceErrorCode;
import se.sll.service.catalogue.common.exception.ValidationException;
import se.sll.service.catalogue.export.ejb.UpdatedOffersTimer;

/**
 * Facade exposing methods for configuration
 * @author Jiri Uosukainen
 */
@Path("/config")
@Slf4j
@Stateless
public class ConfigFacadeREST {

    @EJB
    UpdatedOffersTimer updatedOffersTimer;

    @POST
    @Path("offers/schedule")
    public void setScheduleOffersNotification(@QueryParam("hour") List<Integer> hours) throws ServiceCatalogueException, ValidationException {

        log.info("Indata hours: {}", hours);

        // Valid input
        /* - Not Empty or Null
         * - No duplicates
         * - value range [0,23]
         */

        if (hours != null && !hours.isEmpty()) {
            // Create Schedule
            try {
                TreeSet<Integer> set = new TreeSet(hours);
                log.info("Sorted set: {}", set);
                StringBuilder strb = new StringBuilder("");
                for (int i = 0; i < set.size(); i++) {
                    Integer integer = hours.get(i);
                    if (0 <= integer && integer <= 23) {
                        strb.append(integer.toString());
                        if (i < (set.size() - 1)) {
                            strb.append(",");
                        }
                    }
                }
                // Call timer controller
                updatedOffersTimer.setTimerSchedule(strb.toString());
            }
            catch (RuntimeException e) {
                log.warn("Caught Exception: {}, Message: {} ", new Object[]{e.getClass().getName(), e.getMessage()});
                throw new ServiceCatalogueException(ServiceErrorCode.EXPORT_INVALID_HOURS, "Internal Server error");
            }
        }
        else {
            log.info("Indata validation failed: hours = {}", hours);
            throw new ValidationException(ServiceErrorCode.EXPORT_INVALID_HOURS, "Invalid input: " + hours);
        }
    }
}
